#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time       : 2021/12/13 15:47
@Author     : Boyka
@Contact    : zhw@s.upc.edu.cn
@File       : main.py
@Project    : PID-Core-Algorithms
@Description:
"""

import json
import logging
import os
import datetime
from flask import Flask, request, make_response

# from Padim import test

app = Flask(__name__)
TASKDICT = dict()
MAX_TASK_NUM = 5
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


@app.route('/task', methods=['POST'])
def task():
    data = request.files['file']
    # file_name = data.filename
    info = request.form.to_dict()
    logger.info(info)
    task_id = datetime.datetime.now().strftime('%Y%m%d_%H%M%S%f')
    task_page_path = './images'
    if not os.path.exists(task_page_path):
        os.makedirs(task_page_path)

    # # file_path = r'./Padim/dataset/mvtec_anomaly_detection/big/test/good/'
    # file_path = r'E:\play\flask\picture_test\Padim\dataset\mvtec_anomaly_detection\big\test\good'
    # if data:
    #     # 地址拼接
    #     file_paths = os.path.join(file_path, file_name)
    #     # 保存接收的图片到桌面
    #     data.save(file_paths)

    save_path = os.path.join(task_page_path, "{}.png".format(task_id))
    data.save(save_path)
    print(666666)
    # with open(page_path, "wb") as fw:
    #     fw.write(data)
    # return {'vis_path': 'http://172.19.138.187:10000/vis/{}'.format(task_id)}
    # return {'vis_path': 'http://172.25.216.220/image/{}'.format(task_id)}
    return {'vis_path': 'http://172.25.216.220:5000/image/cat.jpg'}


@app.route('/vis/<string:image_id>', methods=['GET'])
def analysis_visualization(image_id):
    print(66666)
    analysis_file = os.path.join('images', f"{image_id}.png")
    logger.info(analysis_file)
    try:
        image_data = open(analysis_file,
                          "rb").read()
        response = make_response(image_data)
        response.headers['Content-Type'] = 'image/png'
        return response
    except Exception as e:
        logger.info(e)
        return {"status": 0, "result": {}}


if __name__ == '__main__':
    # Set the available cuda devices(GPU 0,1)
    app.run(host="0.0.0.0", port=6000)
